
#include "fig_player_craft.h"
#include "fig_vars.h"
#include "fighter.h"

#include "input/moga.h"

#include "util/log.h"				// log

FIGPlayerCraft::Tilt::Tilt() : m_ToGetOrigin(false)
{  

}

void	FIGPlayerCraft::Tilt::Tick(float dt,
								   math::Vec2& ShipPos,
								   const math::Vec2& ShipSize
								   )
{
    if(m_Dir.x == 0 && m_Dir.y ==0)
		return;

	math::Vec2 Dir = m_Dir * dt * 0.5f;
	const float HalfX = ShipSize.x * 0.5f;
	const float HalfY = ShipSize.y * 0.5f;
    
	math::Vec2 Offset = Fighter::Instance().GetOffset();
    
	if(ShipPos.x + Offset.x + HalfX >= 1.0f && Dir.x > 0)
		Dir.x = 0;
    
	if(ShipPos.x + Offset.x - HalfX <= 0.0f && Dir.x < 0)
		Dir.x = 0;
    
	if(ShipPos.y + HalfY >= 1.0f && Dir.y > 0)
		Dir.y = 0;
    
	if(ShipPos.y - HalfY <= 0.0f && Dir.y < 0)
		Dir.y = 0;

	//Dir.y *= GraphicsUtil::W2H;
    
    ShipPos += Dir;

#ifndef _PLATFORM_IOS
	if(input::MOGAJoystick::Instance().IsConnected() == false)
		m_Dir.x = m_Dir.y = 0; // reset it

#endif
}

void	FIGPlayerCraft::Tilt::OnJoystickTilt(const math::Vec3& AxisState)
{
	if(!GameRMS::Instance()->IsTiltEnabled())
    {
        if(input::MOGAJoystick::Instance().IsConnected() == false)
        {
            m_Dir.x = m_Dir.y = 0;
        }
		return;
    }

	if(input::MOGAJoystick::Instance().IsConnected())
		return;			// disable while we are using MOGA controller analog

    
    //char Buffer[256];
    //sprintf(Buffer, "Tilting: %f: %f", AxisState.GetX(),AxisState.GetY());
    //_LOG(MSG_COMMENT, Buffer);
    
	 if(m_ToGetOrigin)
    {
        math::Vec3 Temp = input::Joystick::Instance().GetAxisState();
		m_Origin = math::Vec2(Temp.x,Temp.y);
        m_ToGetOrigin = false;
    }
    
    
	m_Dir = math::Vec2(AxisState.x,AxisState.y) - m_Origin;
	m_Dir.y *= -1.0f;		// I screwed engine code
    
    
    float CompareTemp = 0.0f;
    
    CompareTemp = 250.0f;
    
    
    if(m_Dir.x < CompareTemp && 
       m_Dir.y < CompareTemp && 
       m_Dir.x > -CompareTemp && 
       m_Dir.y > -CompareTemp
       )
    {
        m_Dir.x = m_Dir.y = 0;
        return;
    }
    
    
    m_Dir.Normalize();
    const float W2H = ( (float)GetGraphics()->GetScreenWidth() / (float)GetGraphics()->GetScreenHeight());
    m_Dir.y *= W2H;
	m_Dir.y *= -1;
	
    
}


void		FIGPlayerCraft::OnMOGAMotionEvent(float X,float Y)
{
	m_Tilt.OnMOGAMotion(X,Y);
}


void		FIGPlayerCraft::Tilt::OnMOGAMotion(float X,float Y)
{
	m_Dir.x = X;
	m_Dir.y = Y;

	m_Dir.y *= GraphicsUtil::W2H;
	m_Dir *= 1.5f;	// move faster
}

void		FIGPlayerCraft::Tilt::MouseMove(const math::Vec2& From, const math::Vec2& To)
{
		

	m_PreviousPosition = To;
}



